/**
 * Created by Jacky.Gao on 2017-01-25.
 */
import Context from "./Context.js";
import ReportTable from "./table/ReportTable.js";
import * as utils from "./Utils.js";

import { undoManager } from "./Utils.js";
import PrintLine from "./PrintLine.js";
import { renderRowHeader } from "./table/HeaderUtils.js";
import $ from "jquery";
import eventBus from "@/utils/eventBus";
import { Message } from "element-ui";

export default class UReportDesigner {
  static server = "http://localhost:8888/ureport_keep";
  constructor (containerId, vue) {
    this.vue = vue;
    this.server = vue.common.ureportDomain;

    if (containerId) {
      undoManager.setLimit(100);
      this.prefix = "file:";
      this.fileFullName = null; // 文件完整名
      this.fileName = null; // 文件名
      this.container = $("#" + containerId);
      const tableContainer = $(`<div></div>`);
      this.container.append(tableContainer);
      this.reportTable = new ReportTable(tableContainer.get(0), this);

      let file = utils.getParameter("_u");
      if (!file) {
        file = "classpath:static/template/template.ureport.xml";
      }
      this.loadFile(file);
    }
  }

  async ajax (url, data, callback) {
    const userInfo = this.vue.common.getUserInfo();
    this.vue.common.loading(true);
    return new Promise((resolve, reject) => {
      $.ajax({
        url: this.server + url,
        data: data,
        type: "POST",
        beforeSend: request => {
          request.setRequestHeader("accessToken", userInfo.accessToken);
          request.setRequestHeader("userFolder", userInfo.keys);
        },
        success: res => {
          if (typeof callback === "function") callback(res);
          this.vue.common.loaded(true);
          resolve(res);
        },
        error: res => {
          this.vue.common.loaded(true);
          if (res && res.responseText) {
            Message.error("服务端错误：" + res.responseText + "");
          } else {
            Message.error(`服务器端请求失败，${res.message}`);
          }
          resolve(res);
        }
      });
    });
  }

  loadFile (file) {
    this.fileInfo(file);
    const _this = this;
    this.reportTable.loadFile(file, function () {
      _this.context = new Context(this);
      this.bindSelectionEvent(function (rowIndex, colIndex, row2Index, col2Index) {
        _this.vue.$set(_this, "rowIndex", rowIndex);
        _this.vue.$set(_this, "colIndex", colIndex);
        _this.vue.$set(_this, "row2Index", row2Index);
        _this.vue.$set(_this, "col2Index", col2Index);
        const cellName = _this.context.getCellName(rowIndex, colIndex);
        _this.vue.$set(_this, "cellName", cellName);
        const cellDef = _this.context.getCell(rowIndex, colIndex); // 单元格数据
        _this.vue.$set(_this, "cellDef", cellDef);
      });

      _this.printLine = new PrintLine(_this.context);
      const rows = _this.context.reportDef.rows;
      for (const row of rows) {
        const band = row.band;
        if (!band) {
          continue;
        }
        _this.context.addRowHeader(row.rowNumber - 1, band);
      }
      renderRowHeader(_this.context.hot, _this.context);
      // 数据加载完毕后事件
      eventBus.$emit("bi-data-load-after", { designer: _this, context: _this.context });
    });
  }
  save (fileName) {
    const { context } = this;
    if (!fileName) {
      Message.error(`请输入文件名！`);
      return;
    }
    if (!this.prefix) {
      Message.error(`请选择文件保存地！`);
      return;
    }
    const userInfo = this.vue.common.getUserInfo();
    const saveFileName = `${this.prefix}${userInfo.userProduct_Id}.${fileName}.ureport.xml`;
    const content = utils.tableToXml(context);

    const url = "/designer/saveReportFile";
    const data = { file: saveFileName, content: content };
    this.ajax(url, data, res => {
      if (res.code === 200) {
        Message.success(`报表文件保存成功`);
        this.fileName = fileName;
        context.isModify = false;
      } else {
        Message.error(`报表文件保存失败：${res.msg}`);
      }
    });
  }
  deleteFile (fileName) {
    if (!fileName) {
      Message.error(`请输入文件名！`);
      return;
    }
    if (!this.prefix) {
      Message.error(`请选择文件保存地！`);
      return;
    }
    const saveFileName = `${this.prefix}${fileName}`;

    const url = "/designer/deleteReportFile";
    const data = { file: saveFileName };
    this.ajax(url, data, res => {
      if (res.code === 200) {
        eventBus.$emit("bi-delete-success-after");
        Message.success(`报表文件删除成功`);
      } else {
        Message.error(`报表文件删除失败：${res.msg}`);
      }
    });
  }

  fileInfo (name) {
    const userInfo = this.vue.common.getUserInfo();

    this.fileFullName = name;
    const suffix = ".ureport.xml";
    let pos = name.indexOf(suffix);
    if (pos > -1) {
      name = name.substring(0, pos);
    }
    pos = name.lastIndexOf("/");
    if (pos > -1) {
      name = name.substring(pos + 1);
    }
    name = name.replace("file:", "");
    name = decodeURI(decodeURI(name));

    name = name.replace(userInfo.userProduct_Id + ".", "");
    this.fileName = name;
  }
}
